<?php

declare(strict_types=1);

namespace App\Controller;

use App\Helps\Data;
use App\Model\Menu;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Paginator\Paginator;


/**
 * Class MenuController
 * @package App\Controller
 */
class MenuController extends AbstractController
{

    public function index(RequestInterface $request, ResponseInterface $response)
    {
        $pageSize = (int)$request->input('pageSize', 5);
        $current = (int)$request->input('current', 1);

        $records = Menu::query()->get()->toArray();
        $treeList = Data::listToTree($records, 'id', 'pid', 'children');
        $dataRecords = collect($treeList);
        $pageRecords = $dataRecords->forPage($current, $pageSize);

        return $response->json([
            'pagination' => [
                'total' => $dataRecords->count(),
                'pageSize' => $pageSize,
                'current' => $current,
                'count' => $pageRecords->count()
            ],
            'list' => array_values($pageRecords->toArray())
        ]);
    }

    public function save(int $id, RequestInterface $request, ResponseInterface $response)
    {

        $inputs = $request->inputs(['name', 'pid','icon','path','sort','visible']);

        Menu::query()->updateOrCreate(['id' => $id], $inputs);
        return $response->json(['message' => '操作成功', 'status' => STATUS_SUCCESS]);
    }

    public function detail(int $id, ResponseInterface $response)
    {
        $menuRecords = Menu::query()->selectRaw('name as title,id,pid')->get()->toArray();
        array_walk($menuRecords, function (&$item) {
            $item['key'] = $item['value'] = $item['id'];
        });

        $menusTree = Data::listToTree($menuRecords, 'id', 'pid', 'children');

        if ($id) {
            $record = Menu::query()->find($id);
        }
        return $response->json([
            'data' => [
                'detail' => !empty($record) ? $record->toArray() : null,
                'menusTree' => $menusTree
            ],

        ]);
    }

    public function batchDelete(RequestInterface $request, ResponseInterface $response)
    {
        $ids = $request->input('ids');
        Menu::query()->where('id', $ids)->delete();
        return $response->json(['message' => '操作成功', 'status' => STATUS_SUCCESS]);
    }
}
